<script setup lang="ts">
import type { ButtonOnGetphonenumberEvent } from '@uni-helper/uni-app-types'
import { getPhoneNumberAPI } from '@/apis/getPhoneNumber'
import { loginAPI } from '@/apis/login'
import useStatusBarHeight from '@/composables/statusBarHeight'
import { useUserInfoStore } from '@/store/userInfo'
import { uploadFileAPI } from '@/apis/uploadFile'
import { updateProfileAPI } from '@/apis/updateProfile'
import avatarPlaceholder from '@/static/images/profile/avatar_placeholder.png'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const statusBarHeight = useStatusBarHeight()
const topPadding = computed(() => statusBarHeight.value + uni.upx2px(88) + uni.upx2px(256))

const pid = ref('')
const isAgree = ref(false)
const isShowDialog = ref(false)
const isShowEmpowerDialog = ref(false)

const avatar = ref('')
const nickname = ref('')

onLoad((options) => {
  if (options?.pid)
    pid.value = options?.pid
})

const handleLogin = useThrottleFn(async () => {
  uni.showLoading({ title: '加载中...' })

  // 如果没勾选同意
  if (!isAgree.value) {
    uni.hideLoading()
    uni.showToast({ title: '请先勾选用户协议和隐私政策', icon: 'none' })
    return
  }

  try {
    // 获取用户信息
    const profileRes = await uni.getUserProfile({
      desc: '展示用户信息',
    })
    // 获取 code
    const loginRes = await uni.login()

    const query = () => {
      if (pid.value) {
        return {
          login_type: 'wechat',
          code: loginRes.code,
          iv: profileRes.iv,
          encryptedData: profileRes.encryptedData,
          pid: pid.value,
        }
      }
      else {
        return {
          login_type: 'wechat',
          code: loginRes.code,
          iv: profileRes.iv,
          encryptedData: profileRes.encryptedData,
        }
      }
    }

    // 使用 code 和加密数据换取 userInfo
    const res = await loginAPI(query() as any)
    uni.hideLoading()

    const userInfo = res.data?.data.userinfo

    if (userInfo) {
      userInfoStore.setUserInfo(userInfo)

      if (!userInfo.mobile) {
        isShowDialog.value = true
        return
      }

      if (!uni.getStorageSync('showedEmpower')) {
        isShowEmpowerDialog.value = true
        return
      }

      router.replaceAll('home')
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err) })
    uni.hideLoading()
  }
}, 500)

async function handleGetPhoneNumber(e: ButtonOnGetphonenumberEvent) {
  if (!nickname.value || !avatar.value) {
    uni.showToast({ title: '请先完善昵称和头像', icon: 'none' })
    return
  }
  userInfoStore.setUserInfo({
    ...userInfoStore.userInfo!,
    nickname: nickname.value,
    avatar: avatar.value,
  })
  try {
    const res = await getPhoneNumberAPI({
      code: e.detail.code!,
    }, userInfoStore.userInfo!.token!)

    if (res.data?.code === 1) {
      const phoneNumber = res.data?.data
      const userInfoWithPhoneNumber: UserInfo = { ...userInfoStore.userInfo!, mobile: phoneNumber }
      userInfoStore.setUserInfo(userInfoWithPhoneNumber)

      if (!uni.getStorageSync('showedEmpower')) {
        isShowEmpowerDialog.value = true
        return
      }

      router.replaceAll('home')
    }
    else {
      uni.showToast({ title: '绑定手机号失败', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}

const handleChooseAvatar = useThrottleFn(async (e: any) => {
  const url = e.detail.avatarUrl
  try {
    const res = await uploadFileAPI({ tempFilePath: url, fileType: 'image' }, userInfoStore.userInfo!.token!)
    if (res.data) {
      const resData = JSON.parse(res.data)
      const uploadRes = await updateProfileAPI({
        nickname: userInfoStore.userInfo?.nickname || '',
        avatar: resData.data.fullurl,
      }, userInfoStore.userInfo!.token!)
      if ((uploadRes.data as any).code === 1)
        avatar.value = resData.data.fullurl
      else
        uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
    }
    else {
      uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
  }
}, 1000)

function handleViewProtocol(type: string) {
  router.push({
    name: 'protocol',
    params: { type },
  })
}

/* ------------------------------- 授权通知 START ------------------------------- */
const isShowTipImage = ref(false)

function handleConfirmEmpower() {
  isShowEmpowerDialog.value = false
  isShowTipImage.value = true
  uni.requestSubscribeMessage({
    tmplIds: [
      'Atj-q7fzQGug9B0zZA9KA0kKYBqacGPC_2RGDU6DvxM',
      'H-Gu6A4sFU8gTgWPAjN4m04CrwLy3JYgHn0bG87sV2E',
      '9UWwae3mpjD-AFJZPvgniZsBcBIDboiRyCOvlLQFm4E',
    ],
    success: () => {
      isShowTipImage.value = false
      uni.setStorageSync('showedEmpower', true)
      router.replaceAll('home')
    },
  })
}
/* -------------------------------- 授权通知 END -------------------------------- */
</script>

<template>
  <NavigationBar title="登录" front-color="#ffffff" />
  <!-- 渐变背景 -->
  <view class="absolute left-0 top-0 h-screen w-screen from-#4999F7 to-#78D9FE to-opacity-0 bg-gradient-to-b" />
  <image class="absolute left-0 top-0 h-392rpx w-333rpx" src="@/static/images/o_bg_tl.png" />
  <image class="absolute right-0 top-589rpx h-484rpx w-197rpx" src="@/static/images/o_bg_br.png" />
  <view class="relative h-screen flex flex-col items-center justify-between">
    <view class="flex flex-col items-center">
      <Spacer :height="topPadding" unit="px" />
      <image class="h-209rpx w-192rpx" src="@/static/images/login_logo.png" />
      <Spacer height="38" />
      <view class="text-52rpx text-white font-semibold leading-73rpx">
        欢迎使用国凤口腔
      </view>
    </view>
    <view class="flex flex-col items-center">
      <button class="h-120rpx w-640rpx flex items-center justify-center rounded-10rpx from-#4999F7 to-#77DAFE bg-gradient-to-r text-36rpx text-white font-medium" @tap="handleLogin">
        手机号快捷登录
      </button>
      <Spacer height="24" />
      <view class="flex items-center" @tap="isAgree = !isAgree">
        <Checkbox :checked="isAgree" />
        <Spacer width="16" />
        <view class="text-24rpx text-#4D4D4D leading-32rpx">
          阅读并同意
          <text class="text-#4999F7" @tap.stop="handleViewProtocol('用户协议')">
            《用户协议》
          </text>
          和
          <text class="text-#4999F7" @tap.stop="handleViewProtocol('隐私政策')">
            《隐私政策》
          </text>
        </view>
      </view>
      <Spacer height="232" />
    </view>
  </view>

  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog v-if="isShowDialog" @cancel="isShowDialog = false">
            <template #all>
              <view class="flex flex-col items-center">
                <Spacer height="72" />
                <view class="text-40rpx text-#333333 font-semibold leading-56rpx">
                  完善信息
                </view>
                <Spacer height="24" />
                <view class="mx-48rpx text-32rpx text-#333333 leading-45rpx">
                  为给您提供更好的服务，请填写以下信息
                </view>
              </view>
              <Spacer height="40" />
              <form>
                <button
                  open-type="chooseAvatar" :style="{ padding: 0, margin: 0, background: 'none' }"
                  @chooseavatar="handleChooseAvatar"
                >
                  <ListCell label="头像">
                    <image class="my-20rpx h-80rpx w-80rpx rounded-full" :src="avatar || avatarPlaceholder" />
                  </ListCell>
                </button>
                <Divider color="#F0F0F0" />
                <ListCell label="昵称">
                  <input
                    v-model="nickname"
                    name="nickname"
                    class="h-116rpx rounded-10rpx bg-white text-right text-28rpx text-#333333 leading-28rpx"
                    placeholder="请输入昵称"
                  >
                </ListCell>
              </form>
              <Spacer height="40" />
              <view class="flex items-center">
                <button open-type="getPhoneNumber" class="h-137rpx w-620rpx flex items-center justify-center rounded-none bg-#4999F7 text-36rpx text-white font-medium leading-50rpx" @getphonenumber="handleGetPhoneNumber">
                  绑定手机号
                </button>
              </view>
            </template>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>

  <uv-overlay :show="isShowEmpowerDialog" @tap="isShowEmpowerDialog = false">
    <uv-transition mode="zoom-in" :show="isShowEmpowerDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog v-if="isShowEmpowerDialog" @cancel="isShowEmpowerDialog = false">
            <template #all>
              <view class="flex flex-col items-center">
                <Spacer height="72" />
                <view class="text-40rpx text-#333333 font-semibold leading-56rpx">
                  开启消息通知
                </view>
                <Spacer height="24" />
                <view class="mx-48rpx text-32rpx text-#333333 leading-45rpx">
                  将第一时间为您推送复诊通知，以及就诊服务等消息
                </view>
              </view>
              <Spacer height="40" />
              <view class="flex items-center">
                <button class="h-137rpx w-620rpx flex items-center justify-center rounded-none bg-#4999F7 text-36rpx text-white font-medium leading-50rpx" @tap="handleConfirmEmpower">
                  立即打开
                </button>
              </view>
            </template>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>

  <image
    v-if="isShowTipImage"
    class="absolute top-200rpx z-40 h-465rpx w-517rpx x-center"
    src="@/static/images/tip.png"
  />
</template>

<route lang="yaml">
name: 'login'
style:
  navigationStyle: 'custom'
layout: 'custom'
</route>
